package com.cloudwise.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2021/9/18 9:25
 * @description：登录过滤器，放行认证之后的用户操作，拦截非法用户
 * 让他滚，滚去登录
 * @modified By：
 * @version: 1.0
 */
//@WebFilter(urlPatterns = "/*")
public class LoginFilter   implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //放行认证之后（session中是否有Username）的用户操作,登录页面放行,失败页面放行，登录的servlet也要放行
        HttpServletRequest requet= (HttpServletRequest) servletRequest;
        HttpSession session = requet.getSession();
        Object useranme = session.getAttribute("sessionUseranme");
        //获取请求的路径
        String requestURI = requet.getRequestURI();
        if(useranme!=null||requestURI.contains("login")||requestURI.contains("fail")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else
        {
            //其他情况，统一滚回登录页面
            HttpServletResponse response= (HttpServletResponse) servletResponse;
            response.sendRedirect("login.jsp");

        }

    }

    @Override
    public void destroy() {

    }
}
